package netTracker.network;

/**
 * Represents a Node in a network.
 * @author David Cummings
 *
 */
public class Node {

	Address localAddress;
	AddressFactory myAddrFactory;
	PostOffice pobox;
	SpanTree mySpanTree;

	/**
	 * Creates a node with a specified hostname and port.
	 * @param hostname the hostname of the node
	 * @param port the port of the node
	 * @throws PostalException
	 */
	public Node(String hostname, int port) 
			throws PostalException{
		localAddress = new Address (hostname, port);
		pobox = new PostOffice (localAddress);
		myAddrFactory = new AddressFactory(pobox);		
		// Make an address complete with unique ID by querying nameServer:
		localAddress = myAddrFactory.makeAddress(localAddress);	
		System.out.println("Joined name server. Address: "+localAddress);
		// Make a spanning tree object but don't start electing:
		mySpanTree = new SpanTree(this, false);
	}

	public PostOffice getPO(){
		return pobox;
	}
	
	public Address getAddress(){
		return localAddress;
	}
	
	public int getID(){
		return localAddress.getID();
	}
	
	public boolean isLeader(){
		return mySpanTree.isLeader();
	}
	
	public String getChildren(){
		return mySpanTree.getChildren();
	}
	
	public String getParent(){
		return mySpanTree.getParent();
	}
	
	/**
	 * Starts an election by making a new spanning tree with self as root.
	 */
	public void startElection() throws PostalException{
		mySpanTree = new SpanTree(this, true);
	}
}